import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {Consts} from '../../../config/consts';
import {BaseService} from '../../../shared/service/base.service';
import {ApiUrl} from '../../../config/api-url';
import {Router} from '@angular/router';

@Component({
  selector: 'app-user-update-pwd',
  templateUrl: './user-update-pwd.component.html',
  styleUrls: ['./user-update-pwd.component.less']
})
export class UserUpdatePwdComponent implements OnInit {
  @Input() isVisible: any;
  @Output()
  emit: EventEmitter<any> = new EventEmitter();
  formModel: FormGroup;
  // 提交时提交按钮是否加载中
  isOkLoading: any;

  constructor(private fb: FormBuilder, private baseService: BaseService, private router: Router) {
  }

  ngOnInit(): void {
    this.buildForm();
  }

  buildForm() {
    this.formModel = this.fb.group({
      password: [null, [Validators.required]],
      newPassword: [null, [Validators.required]],
      confirm: ['', [this.confirmValidator]],
    });
  }

  handleCancel() {
    this.isVisible = false;
    this.emit.emit(this.isVisible);
    this.formModel.reset({});
  }

  validateConfirmPassword(): void {
    setTimeout(() => this.formModel.controls.confirm.updateValueAndValidity());
  }

  //验证密码一至性
  confirmValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return {error: true, required: true};
    } else if (control.value !== this.formModel.controls.newPassword.value) {
      return {confirm: true, error: true};
    }
    return {};
  };

  handleOk() {
    if (this.baseService.zorro.validateFormValidate(this.formModel)) {
      // let body = {
      //   'password': this.baseService.aesEncryption(this.formModel.value.password).toString(),
      //   'newPassword': this.baseService.aesEncryption(this.formModel.value.newPassword).toString()
      // };
      this.isOkLoading = true;
      let body = {
        password: this.formModel.value.password,
        newPassword: this.formModel.value.newPassword
      };
      this.baseService.put(ApiUrl.UserUrl + '/updatePwd', body).subscribe(data => {
        if (data.status == 0) {
          this.isOkLoading = false;
          this.handleCancel();
          sessionStorage.removeItem(Consts.ACCESS_TOKEN);
          sessionStorage.removeItem(Consts.USER_INFO);
          sessionStorage.clear();
          this.router.navigateByUrl('/login');
        } else {
          this.isOkLoading = false;
          this.baseService.layer.messageError(data.msg);
        }
      });
    }
  }

}
